package pers.corvey.studyjava.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.corvey.studyjava.dao.AttachmentDAO;
import pers.corvey.studyjava.dao.ExampleDAO;
import pers.corvey.studyjava.exception.BadRequestException;
import pers.corvey.studyjava.model.Attachment;
import pers.corvey.studyjava.model.Example;

@Service
public class ExampleService {

    @Autowired
    private ExampleDAO exampleDAO;
    
    @Autowired
    private AttachmentDAO attachmentDAO;
    
    public Iterable<Example> getExamples() {
        return exampleDAO.findAll();
    }
    
    public Example getExampleById(String exampleId) {
        return exampleDAO.findOne(exampleId);
    }
    
    public Example createExample(Example example) {
        Iterable<Attachment> attachments = example.getAttachment(); 
        for (Attachment attachment : attachments) {
            attachment.setGmtCreate(new Date());
            attachment.setGmtModified(new Date());
        }
        attachmentDAO.save(attachments);
        example.setGmtCreate(new Date());
        example.setGmtModified(new Date());
        return exampleDAO.save(example);
    }
    
    public Example updateExample(Example example) {
        if (!exampleDAO.exists(example.getId())) {
            throw new BadRequestException("操作失败，不存在对应记录！");
        }
        example.setGmtModified(new Date());
        return exampleDAO.save(example);
    }
    
    public void deleteExampleById(String exampleId) {
        exampleDAO.delete(exampleId);
    }
}
